import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

// 布局组件
import MainLayout from '@/components/personalCenter/MainLayout.vue'

// 路由懒加载 - 个人中心模块
const ProfilePage = () => import('@/components/personalCenter/ProfilePage.vue')
const SettingsPage = () => import('@/components/personalCenter/SettingsPage.vue')
const FavoritesPage = () => import('@/components/personalCenter/FavoritesPage.vue')
const FollowingPage = () => import('@/components/personalCenter/FollowingPage.vue')
const RecommendList = () => import('@/components/personalCenter/RecommendationList.vue')
const NotFound = ()=>import('@/components/error/NoteFound.vue')

// 路由懒加载 - 视频模块
const HomePage = () => import("@/components/home/HomePage.vue")
const VideoPlayback = () => import('@/components/video/VideoPlayback.vue')
const VideoUpload = () => import('@/components/VideoUpload.vue')

// 路由懒加载 - 认证模块
const UserLogin = () => import('@/components/auth/UserLogin.vue')
const UserRegister = () => import('@/components/auth/UserRegister.vue')

const routes = [
    {
        path: '/',
        redirect: '/home',
        meta: { title: 'aliali' },
    },
    {
        path: '/home',
        name: 'Home',
        component: HomePage,
        meta: {
            title: '首页 - aliali',
            keepAlive: true,
            requiresAuth: false
        }
    },
    {
        path: '/video/:id',
        name: 'VideoPlayback',
        component: VideoPlayback,
        meta: {
            title: '视频播放 - aliali',
            requiresAuth: false
        },
        props: true
    },
    {
        path: '/upload',
        name: 'VideoUpload',
        component: VideoUpload,
        meta: {
            title: '投稿中心 - aliali',
            requiresAuth: true
        }
    },
    {
        path: '/user',
        component: MainLayout,
        redirect: '/user/profile',
        meta: { requiresAuth: true },
        children: [
            {
                path: 'profile',
                name: 'UserProfile',
                component: ProfilePage,
                meta: {
                    title: '个人主页 - aliali',
                    keepAlive: true
                }
            },
            
            {
                path: 'settings',
                name: 'UserSettings',
                component: SettingsPage,
                meta: {
                    title: '账号设置 - aliali',
                    requiresAuth: true
                }
            },
            {
                path: 'favorites',
                name: 'UserFavorites',
                component: FavoritesPage,
                meta: {
                    title: '我的收藏 - aliali',
                    keepAlive: true,
                    requiresAuth: true
                }
            },
            {
                path: 'following',
                name: 'UserFollowing',
                component: FollowingPage,
                meta: {
                    title: '我的关注 - aliali',
                    keepAlive: true,
                    requiresAuth: true
                }
            },
            {
                path: 'recommend',
                name: 'UserRecommend',
                component: RecommendList,
                meta: {
                    title: '推荐关注 - aliali',
                    requiresAuth: true
                }
            }
        ]
    },
    {
        path: '/login',
        name: 'UserLogin',
        component: UserLogin,
        meta: {
            title: '用户登录 - aliali',
            requiresAuth: false
        }
    },
    {
        path: '/register',
        name: 'UserRegister',
        component: UserRegister,
        meta: {
            title: '用户注册 - aliali',
            requiresAuth: false
        }
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: NotFound,
        meta: { title: '页面未找到 - aliali' }
    }
]

const router = createRouter({
    // 修复这一行：使用正确的环境变量引用方式
    history: createWebHistory(import.meta.env?.BASE_URL || process.env?.BASE_URL || '/'),
    routes,
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return { top: 0, behavior: 'smooth' }
        }
    }
})

import Cookies from 'js-cookie'

// 路由守卫
router.beforeEach((to, from, next) => {
    // 设置页面标题
    if (to.meta.title) {
        document.title = to.meta.title
    }

    // 检查是否需要认证
    if (to.meta.requiresAuth) {
        // 优先检查cookie中的satoken，如果没有再检查localStorage中的token
        const token = Cookies.get('satoken') || localStorage.getItem('token')
        console.log(token)
        if (!token) {
            ElMessage.warning('请先登录')
            next({
                name: 'UserLogin',
                query: { redirect: to.fullPath }
            })
            return
        }
    }

    next()
})

router.afterEach((to, from) => {
    // 可以在这里添加统计代码
    console.log(`路由切换: ${from.name} -> ${to.name}`)
})

export default router